﻿using System;
using System.Text.Json;
using AntDesign;
using AntDesign.JsInterop;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;


namespace Diary.Web.Blazor.WASM.Shared
{
    public partial class ContextMenuPanel : AntDomComponentBase
    {
        [Inject]
        protected IDomEventListener DomEventListener { get; set; }
        protected override void OnAfterRender(bool firstRender)
        {
            if (firstRender)
            {
                if (OnContextMenu.HasDelegate)
                {
                    Ref = RefBack.Current;
                    DomEventListener.AddExclusive<JsonElement>(Ref, "contextmenu", ContextMenuHandler, true);
                }
                if (OnClick.HasDelegate)
                {
                    DomEventListener.AddExclusive<JsonElement>(Ref, "click", ClickHandler, false);
                }
            }
            base.OnAfterRender(firstRender);
        }

        [Parameter]
        public RenderFragment ChildContent { get; set; }

        /// <summary>
        /// Right-click tree node callback
        /// </summary>
        [Parameter]
        public EventCallback<MouseEventArgs> OnContextMenu { get; set; }

        [Parameter]
        public EventCallback<MouseEventArgs> OnClick { get; set; }


        protected override void Dispose(bool disposing)
        {
            DomEventListener.DisposeExclusive();
            base.Dispose(disposing);
        }

        protected async void ContextMenuHandler(JsonElement jsonElement)
        {
            var eventArgs = JsonSerializer.Deserialize<MouseEventArgs>(jsonElement.ToString(),
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            await OnContextMenu.InvokeAsync(eventArgs);
        }

        protected async void ClickHandler(JsonElement jsonElement)
        {
            var eventArgs = JsonSerializer.Deserialize<MouseEventArgs>(jsonElement.ToString(),
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            await OnClick.InvokeAsync(eventArgs);
        }
    }
}
